package cc.admin.modules.sys.service.impl;

import cc.admin.modules.sys.entity.SysCascade;
import cc.admin.modules.sys.mapper.SysCascadeMapper;
import cc.admin.modules.sys.service.ISysCascadeService;
import org.springframework.stereotype.Service;

import cc.admin.modules.sys.entity.SysCascadeTree;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 级联设置
 * @Author: cc-admin
 * @Date:   2022-05-18
 * @Version: V1.0.0
 */
@Service
public class SysCascadeServiceImpl extends ServiceImpl<SysCascadeMapper, SysCascade> implements ISysCascadeService {

	@Override
	public List<SysCascadeTree> queryTreeList(QueryWrapper<SysCascade> queryWrapper) {
		List<SysCascade> sysCascadeList = baseMapper.selectList(queryWrapper);
		//规定根节点是0
		return renderTree(sysCascadeList, "0");
	}

	@Override
	public void removeNodeById(String id) {
		QueryWrapper<SysCascade> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("parent_id", id);
		List<SysCascade> sysCascadeList = baseMapper.selectList(queryWrapper);
		if (CollectionUtil.isNotEmpty(sysCascadeList)) {
			sysCascadeList.forEach(sysCascade -> {
				removeNodeById(sysCascade.getId());
			});
		}
		removeById(id);
	}

	/**
	 * 将列表数据转换为树状结构的
	 * @param sysCascadeList
	 * @param parentId
	 * @return
	 */
	public List<SysCascadeTree> renderTree(List<SysCascade> sysCascadeList, String parentId) {
		List<SysCascadeTree> resultList = Lists.newArrayList();
		for (SysCascade sysCascade : sysCascadeList) {
			if (parentId.equals(sysCascade.getParentId())) {
				SysCascadeTree sysCascadeTree = new SysCascadeTree();
				sysCascadeTree.setId(sysCascade.getId());
				sysCascadeTree.setName(sysCascade.getName());
				resultList.add(sysCascadeTree);
				sysCascadeTree.setChildren(renderTree(sysCascadeList, sysCascade.getId()));
			}
		}
		return resultList;
	}
}
